package com.wfm.mianshi.多个线程打印ABCABC;

public class 利用Synchronized {
    static class PrintABC {
        private int state = 0;
        private static final int MAX_TIMES = 3;

        public synchronized void printA() throws InterruptedException {
            for (int i = 0; i < MAX_TIMES; i++) {
                while (state % 3 != 0) {
                    wait();
                }
                System.out.print("A");
                state++;
                notifyAll();
            }
        }

        public synchronized void printB() throws InterruptedException {
            for (int i = 0; i < MAX_TIMES; i++) {
                while (state % 3 != 1) {
                    wait();
                }
                System.out.print("B");
                state++;
                notifyAll();
            }
        }

        public synchronized void printC() throws InterruptedException {
            for (int i = 0; i < MAX_TIMES; i++) {
                while (state % 3 != 2) {
                    wait();
                }
                System.out.print("C");
                state++;
                notifyAll();
            }
        }
    }
    public static void main(String[] args) {
        PrintABC printABC = new PrintABC();

        Thread threadA = new Thread(() -> {
            try {
                printABC.printA();
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        });

        Thread threadB = new Thread(() -> {
            try {
                printABC.printB();
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        });

        Thread threadC = new Thread(() -> {
            try {
                printABC.printC();
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        });

        threadA.start();
        threadB.start();
        threadC.start();

        try {
            threadA.join();
            threadB.join();
            threadC.join();
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }

}
